/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-30
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-16
 * @Description:
 */
/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-30
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-08
 * @Description: 数据本地读写 ，单例模式
 */
import 'package:chat_client/models/conversation_model.dart';
import 'package:chat_client/repositories/hive_repository.dart';

import 'package:hive/hive.dart'; //聊天列表

/// 会话本地存储
class ConversationRepository {
  // 单例
  ConversationRepository._internal();
  static final ConversationRepository _instance =
      ConversationRepository._internal();
  static ConversationRepository get instance => _instance;

  // 打开数据库
  final _hive = HiveService.instance;
  late final Box<Conversation> _conversationBox;
  late final Box<Message> _messageBox;
  Future<void> init() async {
    _conversationBox = await _hive.openBox('conversation');
    _messageBox = await _hive.openBox('message');
  }

  // 储存单个会话
  Future<void> setConversation(Conversation conversation) async {
    // 将conversationId作为key
    await _conversationBox.put(conversation.conversationId, conversation);
  }

  // 储存单条信息
  Future<void> setMessage(Message message) async {
    // 将messageId作为key
    await _messageBox.put(message.messageId, message);
  }

  // 获取单个会话, 不存在则直接创建
  Conversation? getConversation(String conversationId) {
    Conversation? conversation = _conversationBox.get(conversationId);
    // 如果会话不存在则直接创建临时新会话
    return conversation;
  }

  // 根据消息ID列表获取完整消息对象，自动跳过无效ID
  List<Message> getConversationDetaile(String conversationId) {
    final Conversation? conversation = getConversation(conversationId);
    if (conversation == null || conversation.messages.isEmpty) return [];

    final toList = conversation.messages
        .map((messageId) => _messageBox.get(messageId)) // 转换ID为Message对象
        .where((message) => message != null) // 过滤掉null值
        .cast<Message>() // 类型转换保障
        .toList(); // 转换为结果列表
    print('根据消息ID列表获取完整消息对象，自动跳过无效ID${toList.length}');

    // 修改conversation的列表
    if (toList.length < conversation.messages.length) {
      // 不等待它执行完成！！
      updateCoversation(conversation);
    }

    return toList;
  }

  // 获取会话列表（按最后活跃时间倒序）
  List<Conversation> getConversationList() {
    return _conversationBox.values.toList()
      ..sort((a, b) => b.lastActive.compareTo(a.lastActive)); // 降序排序
  }

  // 删除单条消息
  Future<void> delete(String messageId) async {
    await _messageBox.delete(messageId);
    // 修改
  }

  // 修改conversation的列表
  Future<void> updateCoversation(Conversation conversation) async {
    final toList = conversation.messages
        .where((messageId) => _messageBox.get(messageId) != null) // 过滤掉null值
        .toList(); // 转换为结果列表
    conversation.copyWith(
        messages: toList, lastMessage: toList[toList.length - 1]);
    setConversation(conversation);
  }
}
